package com.xzlf.config;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xzlf.domain.SpringScheduledCron;
import com.xzlf.job.ScheduleOfTask;
import com.xzlf.mapper.SpringScheduledCronMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

@Configuration
public class ScheduledConfig implements SchedulingConfigurer {

    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private SpringScheduledCronMapper springScheduledCronMapper;


    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        List<SpringScheduledCron> springScheduledCrons = springScheduledCronMapper.selectList(null);
        for (SpringScheduledCron scheduledCron : springScheduledCrons) {
            Class<?> clz;
            ScheduleOfTask task = null;
            try {
                clz = Class.forName(scheduledCron.getCronKey());
                task = (ScheduleOfTask) applicationContext.getBean(clz);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }

            // 可以通过改变数据库数据进而实现动态改变执行周期
            assert task != null;
            taskRegistrar.addTriggerTask(task, triggerContext -> {
                String cronExpression = springScheduledCronMapper.selectOne(new LambdaQueryWrapper<SpringScheduledCron>()
                        .eq(SpringScheduledCron::getCronKey, scheduledCron.getCronKey()))
                        .getCronExpression();
                return new CronTrigger(cronExpression).nextExecutionTime(triggerContext);
            });
        }
    }

    /**
     * springboot默认会创建一个单线程的线程池
     * @return
     */
    @Bean
    public Executor taskExectuor() {
        return Executors.newScheduledThreadPool(10);
    }
}
